import axios from "axios";
import store from "@/store";
import { getToken } from "@/utils/auth";
import { logout } from "@/store/actions";

//创建一个axios示例
const service = axios.create({
  baseURL: process.env.REACT_APP_BASE_API, // api 的 base_url
  timeout: 30* 1000, // request timeout
});

// 请求拦截器
service.interceptors.request.use(
  (config) => {
    if (store.getState().user.token) {
      config.headers.Authorization = 'Bearer ' + getToken();
    }
    return config;
  },
  (error) => {
    console.log(error); // for debug
    Promise.reject(error);
  }
);

// 响应拦截器
service.interceptors.response.use(
  (response) => {
    const { data } = response;
    if (data.code === 200) {
      return data;
    } else if (data.code === 401) {
      const token = store.getState().user.token;
      store.dispatch(logout(token));
      return Promise.reject(data);
    } else {
      return Promise.reject(data.message);
    }
  },

  (error) => {
    console.log("err" + error); // for debug
    return Promise.reject(error);
  }
);

export default service;
